package bdhub.littletail;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;

import bdhub.littletail.app.process.main.IMainReceiver;
import bdhub.littletail.app.process.main.MainService;
import bdhub.littletail.lib.utils.log.CLog;

public class MainActivity extends Activity implements View.OnClickListener {

    private MainActivity mContext;
    private IMainReceiver mMainReceiver;
    private Button btn1, btn2, btn3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initWidget();
        initMainService();
        setListeners();
    }

    private void initWidget() {
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
    }

    private void setListeners() {
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
    }

    private void initMainService() {
        ServiceConnection connection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                CLog.d(MainActivity.class.getSimpleName(), "onServiceConnected()");
                mMainReceiver = IMainReceiver.Stub.asInterface(service);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

        bindService(new Intent(mContext, MainService.class), connection, BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1 :
                try {
                    mMainReceiver.onReceiverMessage(null);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.btn2 :
                try {
                    mMainReceiver.updateState(0);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;

            case R.id.btn3 :
                try {
                    mMainReceiver.stopService();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
